// 历史数据回放模块 - 负责历史数据的记录、存储和回放

class HistoryPlayback {
    constructor() {
        this.records = [];
        this.isRecording = false;
        this.isPlaying = false;
        this.playbackSpeed = 1.0;
        this.playbackPosition = 0;
        this.playbackInterval = null;
        this.maxRecords = 10000;
        this.listeners = {};
        this.recordStartTime = null;
        this.playbackStartTime = null;
        this.dataStores = {};
        this.storageKey = 'realtime_system_history';
    }

    // 初始化历史回放模块
    init() {
        console.log('历史数据回放模块初始化...');
        
        // 加载本地存储的历史记录
        this.loadFromStorage();
        
        // 监听数据更新
        if (realTimeSystem.modules.dataStream) {
            const dataStream = realTimeSystem.modules.dataStream;
            dataStream.on('realtime:updated', this.handleDataUpdate.bind(this));
            dataStream.on('finance:updated', this.handleDataUpdate.bind(this));
            dataStream.on('iot:updated', this.handleDataUpdate.bind(this));
            dataStream.on('system:updated', this.handleDataUpdate.bind(this));
        }
        
        console.log('历史数据回放模块初始化完成');
    }

    // 开始记录数据
    startRecording() {
        if (this.isRecording) {
            console.warn('已经在记录中');
            return false;
        }
        
        this.isRecording = true;
        this.recordStartTime = Date.now();
        
        console.log('开始记录历史数据');
        this.emit('recording:started', {
            startTime: this.recordStartTime
        });
        
        return true;
    }

    // 停止记录数据
    stopRecording() {
        if (!this.isRecording) {
            console.warn('没有在记录中');
            return false;
        }
        
        this.isRecording = false;
        
        const recordingInfo = {
            startTime: this.recordStartTime,
            endTime: Date.now(),
            duration: Date.now() - this.recordStartTime,
            recordCount: this.records.length
        };
        
        console.log('停止记录历史数据', recordingInfo);
        this.emit('recording:stopped', recordingInfo);
        
        // 保存到本地存储
        this.saveToStorage();
        
        return recordingInfo;
    }

    // 处理数据更新
    handleDataUpdate(data) {
        if (!this.isRecording) return;
        
        const record = {
            timestamp: Date.now(),
            relativeTime: Date.now() - this.recordStartTime,
            dataSource: data.store || data.source || 'unknown',
            data: { ...data }
        };
        
        this.records.push(record);
        
        // 限制记录数量
        if (this.records.length > this.maxRecords) {
            this.records = this.records.slice(-this.maxRecords);
        }
        
        // 批量保存到本地存储（每100条记录）
        if (this.records.length % 100 === 0) {
            this.saveToStorage();
        }
    }

    // 开始回放
    startPlayback(options = {}) {
        if (this.isPlaying) {
            console.warn('已经在回放中');
            return false;
        }
        
        if (this.records.length === 0) {
            console.warn('没有可回放的历史数据');
            return false;
        }
        
        this.isPlaying = true;
        this.playbackPosition = options.startPosition || 0;
        this.playbackSpeed = options.speed || 1.0;
        this.playbackStartTime = Date.now();
        
        // 计算回放开始的相对时间
        const startRecord = this.records[this.playbackPosition];
        const startTimeInRecording = startRecord ? startRecord.relativeTime : 0;
        
        console.log(`开始回放历史数据，位置: ${this.playbackPosition}, 速度: ${this.playbackSpeed}x`);
        
        // 开始回放循环
        this.playbackInterval = setInterval(() => {
            this.playbackStep(startTimeInRecording);
        }, 10); // 每10ms检查一次，确保平滑回放
        
        this.emit('playback:started', {
            startPosition: this.playbackPosition,
            speed: this.playbackSpeed,
            totalRecords: this.records.length
        });
        
        return true;
    }

    // 回放步骤
    playbackStep(startTimeInRecording) {
        if (!this.isPlaying || this.playbackPosition >= this.records.length) {
            this.stopPlayback();
            return;
        }
        
        // 计算当前应该回放的位置
        const elapsedTime = (Date.now() - this.playbackStartTime) * this.playbackSpeed;
        const targetTime = startTimeInRecording + elapsedTime;
        
        // 播放所有应该在这个时间点之前播放的记录
        while (this.playbackPosition < this.records.length && 
               this.records[this.playbackPosition].relativeTime <= targetTime) {
            
            const record = this.records[this.playbackPosition];
            this.emitRecord(record);
            this.playbackPosition++;
        }
    }

    // 发送记录数据
    emitRecord(record) {
        // 如果数据引擎可用，将回放的数据添加到相应的数据存储中
        if (realTimeSystem.modules.dataStream) {
            const dataStream = realTimeSystem.modules.dataStream;
            dataStream.addDataPoint(record.dataSource, record.data);
        }
        
        // 触发回放事件
        this.emit('playback:record', record);
        this.emit(`playback:${record.dataSource}`, record.data);
    }

    // 暂停回放
    pausePlayback() {
        if (!this.isPlaying) return false;
        
        this.isPlaying = false;
        
        if (this.playbackInterval) {
            clearInterval(this.playbackInterval);
            this.playbackInterval = null;
        }
        
        console.log('暂停回放');
        this.emit('playback:paused', {
            position: this.playbackPosition,
            progress: this.getPlaybackProgress()
        });
        
        return true;
    }

    // 继续回放
    resumePlayback() {
        if (this.isPlaying) return false;
        
        // 使用当前位置和速度继续回放
        return this.startPlayback({
            startPosition: this.playbackPosition,
            speed: this.playbackSpeed
        });
    }

    // 停止回放
    stopPlayback() {
        if (!this.isPlaying) return false;
        
        this.isPlaying = false;
        
        if (this.playbackInterval) {
            clearInterval(this.playbackInterval);
            this.playbackInterval = null;
        }
        
        const playbackInfo = {
            finalPosition: this.playbackPosition,
            progress: this.getPlaybackProgress(),
            duration: Date.now() - this.playbackStartTime
        };
        
        console.log('停止回放', playbackInfo);
        this.emit('playback:stopped', playbackInfo);
        
        return playbackInfo;
    }

    // 设置回放位置
    setPlaybackPosition(position) {
        if (position < 0 || position >= this.records.length) {
            console.error('无效的回放位置');
            return false;
        }
        
        this.playbackPosition = position;
        
        console.log(`设置回放位置: ${position}`);
        this.emit('playback:positionChanged', {
            position: position,
            progress: this.getPlaybackProgress()
        });
        
        return true;
    }

    // 设置回放速度
    setPlaybackSpeed(speed) {
        if (speed <= 0) {
            console.error('回放速度必须大于0');
            return false;
        }
        
        this.playbackSpeed = speed;
        
        // 如果正在播放，需要重新计算时间
        if (this.isPlaying) {
            const currentProgress = this.getPlaybackProgress();
            this.stopPlayback();
            this.startPlayback({
                startPosition: Math.floor(this.records.length * currentProgress),
                speed: speed
            });
        }
        
        console.log(`设置回放速度: ${speed}x`);
        this.emit('playback:speedChanged', { speed: speed });
        
        return true;
    }

    // 获取回放进度
    getPlaybackProgress() {
        if (this.records.length === 0) return 0;
        return this.playbackPosition / this.records.length;
    }

    // 清空历史记录
    clearHistory() {
        // 停止所有操作
        this.stopRecording();
        this.stopPlayback();
        
        // 清空记录
        this.records = [];
        this.playbackPosition = 0;
        
        // 清除本地存储
        this.clearStorage();
        
        console.log('历史记录已清空');
        this.emit('history:cleared');
        
        return true;
    }

    // 保存历史记录到本地存储
    saveToStorage() {
        try {
            // 只保存最近的记录，避免占用过多存储空间
            const recordsToSave = this.records.slice(-5000); // 最多保存5000条记录
            
            const dataToSave = {
                records: recordsToSave,
                metadata: {
                    lastSaved: Date.now(),
                    recordCount: recordsToSave.length,
                    maxRecords: this.maxRecords
                }
            };
            
            localStorage.setItem(this.storageKey, JSON.stringify(dataToSave));
            return true;
        } catch (error) {
            console.error('保存历史记录到本地存储时出错:', error);
            return false;
        }
    }

    // 从本地存储加载历史记录
    loadFromStorage() {
        try {
            const storedData = localStorage.getItem(this.storageKey);
            if (!storedData) return false;
            
            const parsedData = JSON.parse(storedData);
            if (parsedData.records && Array.isArray(parsedData.records)) {
                this.records = parsedData.records;
                console.log(`从本地存储加载了 ${this.records.length} 条历史记录`);
                return true;
            }
        } catch (error) {
            console.error('从本地存储加载历史记录时出错:', error);
        }
        
        return false;
    }

    // 清除本地存储
    clearStorage() {
        try {
            localStorage.removeItem(this.storageKey);
            return true;
        } catch (error) {
            console.error('清除本地存储时出错:', error);
            return false;
        }
    }

    // 获取历史记录统计
    getStatistics() {
        // 统计不同数据源的记录数量
        const sourceCounts = {};
        this.records.forEach(record => {
            const source = record.dataSource;
            sourceCounts[source] = (sourceCounts[source] || 0) + 1;
        });
        
        // 计算记录的时间范围
        let timeRange = null;
        if (this.records.length > 0) {
            const firstRecord = this.records[0];
            const lastRecord = this.records[this.records.length - 1];
            timeRange = {
                startTime: firstRecord.timestamp,
                endTime: lastRecord.timestamp,
                duration: lastRecord.timestamp - firstRecord.timestamp
            };
        }
        
        return {
            totalRecords: this.records.length,
            maxRecords: this.maxRecords,
            sourceCounts,
            timeRange,
            isRecording: this.isRecording,
            isPlaying: this.isPlaying,
            playbackPosition: this.playbackPosition,
            playbackSpeed: this.playbackSpeed,
            playbackProgress: this.getPlaybackProgress()
        };
    }

    // 导出历史记录
    exportHistory() {
        const exportData = {
            records: this.records,
            statistics: this.getStatistics(),
            exportedAt: Date.now()
        };
        
        // 创建Blob对象
        const blob = new Blob([JSON.stringify(exportData, null, 2)], {
            type: 'application/json'
        });
        
        // 创建下载链接
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `realtime_system_history_${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
        a.click();
        
        // 清理
        URL.revokeObjectURL(url);
        
        return true;
    }

    // 导入历史记录
    importHistory(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            
            reader.onload = (e) => {
                try {
                    const importedData = JSON.parse(e.target.result);
                    
                    if (importedData.records && Array.isArray(importedData.records)) {
                        // 停止当前操作
                        this.stopRecording();
                        this.stopPlayback();
                        
                        // 导入记录
                        this.records = importedData.records;
                        this.playbackPosition = 0;
                        
                        // 保存到本地存储
                        this.saveToStorage();
                        
                        console.log(`成功导入 ${this.records.length} 条历史记录`);
                        this.emit('history:imported', { recordCount: this.records.length });
                        
                        resolve({ success: true, recordCount: this.records.length });
                    } else {
                        reject(new Error('导入的数据格式不正确'));
                    }
                } catch (error) {
                    reject(error);
                }
            };
            
            reader.onerror = () => {
                reject(new Error('读取文件失败'));
            };
            
            reader.readAsText(file);
        });
    }

    // 注册监听器
    on(event, callback) {
        if (!this.listeners[event]) {
            this.listeners[event] = [];
        }
        this.listeners[event].push(callback);
        
        return () => {
            this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
        };
    }

    // 触发事件
    emit(event, data) {
        if (this.listeners[event]) {
            this.listeners[event].forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`处理${event}事件时出错:`, error);
                }
            });
        }
    }

    // 停止历史回放模块
    stop() {
        this.stopRecording();
        this.stopPlayback();
        console.log('历史数据回放模块已停止');
    }
}

// 创建并注册历史回放模块实例
const historyPlayback = new HistoryPlayback();
realTimeSystem.registerModule('historyPlayback', historyPlayback);

// 导出历史回放模块
window.historyPlayback = historyPlayback;